<?php
declare(strict_types=1);

namespace App\Utils\Other\Payment\Chinapnrpay;

use App\Exception\InternalException;
use Hyperf\Collection\Arr;

/**
 * 微信小程序端
 * @package App\Utils\Other\Payment\Sandpay
 */
Class Mini extends App {

    /**
     * 支付
     * @param array $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function pay(array $params): array
    {
        $this->setConfig([
            'params_sort' => [
                'pageUrl', 'bgUrl', 'merchantAcctId', 'terminalId', 'customerId',
                'orderId', 'orderAmount', 'orderTime', 'productDesc', 'ext1', 'ext2',
                'deviceType', 'payType', 'shortCardno'
            ],
            'path' => 'pay/unifiedorder.htm'
        ]);
        $params['inputCharset'] = '1';
        $params['language'] = '1';
        $params['customerIp'] = getIp();
        $params['settlementCurrency'] = 'CNY';

        [$params, $response, $body] = $this->request($params);
        return [$params, $response, Arr::get($body, 'payInfo')];
    }

    /**
     * 验证
     * @param array $params
     * @return array
     */
    public function verify(array $params): array
    {
        $this->setConfig([
            'params_sort' => [
                'bankDealId', 'bankId', 'dealId', 'dealTime', 'errCode', 'ext1', 'ext2',
                'merchantAcctId', 'orderAmount', 'orderCurrency', 'orderId', 'orderTime',
                'payResult', 'payType', 'terminalId', 'version'
            ]
        ]);

        $this->check($params);

        return $params;
    }

    /**
     * 退款
     * @param array $params
     * @return array
     */
    public function refund(array $params): array
    {
        $this->setConfig([
            'params_sort' => [
                'inputCharset', 'bgUrl', 'version', 'language', 'signType',
                'merchantAcctId', 'terminalId', 'refundOrderId', 'originalOrderId',
                'refundCurrency', 'refundAmount', 'ext1', 'ext2'
            ],
            'path' => 'pay/refundreceive.htm'
        ]);
        $params['inputCharset'] = '1';
        $params['language'] = '1';

        [$params, $response, $body] = $this->request($params);
        if (Arr::get($body, 'refundResult') !== 'C0' && Arr::get($body, 'refundResult') !== '10') {
            throw new InternalException('REFUND FAIL');
        }

        return [$params, $response, $body];
    }

    /**
     * 退款验证
     * @param array $params
     * @return array
     */
    public function refundVerify(array $params): array
    {
        $this->setConfig([
            'params_sort' => [
                'dealId', 'dealTime', 'errCode', 'ext1', 'ext2', 'merchantAcctId',
                'originalOrderId', 'refundAmount', 'refundBalance', 'refundCurrency',
                'refundOrderId', 'refundResult', 'terminalId'
            ]
        ]);

        $this->check($params);

        return $params;
    }
}